package com.example.controller;

import com.example.VO.BorrowRecordVO;
import com.example.entity.User;
import com.example.service.BorrowRecordService;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @auth shanyue
 * @date 2025年06月06日15:09
 */
@Controller
public class ProfileController {

    @Resource
    private UserService userService;

    @Resource
    private BorrowRecordService borrowRecordService;


    @GetMapping("/profile")
    public String profilePage(Model model, Principal principal) {
        User user = userService.findByUsername(principal.getName());
        model.addAttribute("username", user.getUsername());
        model.addAttribute("user", user);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedCreateTime = sdf.format(user.getCreateTime());
        model.addAttribute("formattedCreateTime", formattedCreateTime);

        // 仅 USER 角色展示借阅记录
        if ("USER".equals(user.getRole())) {
            List<BorrowRecordVO> records = borrowRecordService.getBorrowRecordsByUserId(user.getId());
            model.addAttribute("borrowRecords", records);
        }

        return "profile";
    }

    @PostMapping("/user/return/{id}")
    public String returnBook(@PathVariable Integer id) {
        borrowRecordService.returnBook(id);
        return "redirect:/profile";
    }

}
